//
//  ZDEmojiViewController.m
//  ZDEmojiKeyBoard
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDEmojiViewController.h"
#import "ZDCollectionViewFlowLayout.h"
#import "ZDEmojiPackage.h"
#import "ZDTextAttachment.h"
#import "UITextView+Extension.h"

#define ZDBaseIndex 1000

@interface ZDEmojiViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIToolbar *toolBar;

@property (nonatomic, strong) NSArray *emojiPackages;

@property (nonatomic, weak) UIButton *selectedBtn;

@end

@implementation ZDEmojiViewController

static NSString *reuseIdentifier = @"emojiCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self prepareUI];
    
    [self setcollectionView];
    
    [self setToolBar];
}


//准备UI
- (void)prepareUI
{
    //添加子控件
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.toolBar];
    
    
    //添加约束
    _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    _toolBar.translatesAutoresizingMaskIntoConstraints = NO;
    
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[cv]-0-|" options:0 metrics:nil views:@{@"cv" : _collectionView}]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tb]-0-|" options:0 metrics:nil views:@{@"tb" : _toolBar}]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[cv]-0-[tb(44)]-0-|" options:0 metrics:nil views:@{@"cv" : _collectionView, @"tb" : _toolBar}]];
}


- (void)setToolBar
{
    NSMutableArray *items = [NSMutableArray array];
    
    NSUInteger index = 0;
    
    for (ZDEmojiPackage *package in [ZDEmojiPackage emojiPackages])
    {
//        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:dict[@"title"] style:UIBarButtonItemStyleDone target:self action:NSSelectorFromString(dict[@"action"])];
//        
//        item.tintColor = [UIColor redColor];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.tag = index + ZDBaseIndex;
        
        if (index == 0)
        {
            [self switchBtn:btn];
        }
        
        [btn setTitle:package.group_name_cn forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [btn sizeToFit];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        
        [items addObject:item];
        
        //添加弹簧
        [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
        
        index++;
    }
    
    //移除最后一个弹簧
    [items removeLastObject];
    
    self.toolBar.items = items;
}

///barButtonItem回调方法
- (void)btnClick:(UIButton *)btn
{
    if (self.selectedBtn == btn)
    {
        return;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:(btn.tag-ZDBaseIndex)];
    
    //滚动到对应的section
    [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionLeft];
    
    [self switchBtn:btn];
}


///选中btn
- (void)switchBtn:(UIButton *)button
{
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
}

- (void)setcollectionView
{
    //设置数据源和代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    //注册cell
    [_collectionView registerClass:[ZDCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    _collectionView.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1.0];
}

/////textView插入emoji表情
//- (void)insertEmojiWith:(ZDEmoji *)emoji
//{
//    if (!emoji)
//    {
//        return;
//    }
//    
//    //插入emoji表情(本质上就是字符串)
//    if (emoji.emojiString)
//    {
//        [self.textView insertText:emoji.emojiString];
//        
//        return;
//    }
//    
//    //插入表情图片(图片不能通过insertText插入)
//    //创建附件
//    ZDTextAttachment *attachment = [[ZDTextAttachment alloc] init];
//    //给附件添加图片
//    attachment.image = emoji.emojiImage;
//    attachment.name = emoji.chs;
//    
//    //根据文本的高度调整附件图片的bounds
//    CGFloat height = self.textView.font.lineHeight;
//    attachment.bounds = CGRectMake(0, -height * 0.2, height, height);
//    
//    //创建带附件的属性文本
//    NSAttributedString *attributeStr = [NSAttributedString attributedStringWithAttachment:attachment];
//
//    //获取textView的属性文本  转换为可变 属性文本
//    NSMutableAttributedString *attributeStrM = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
//    
//    //获取当前选中的范围
//    NSRange range = self.textView.selectedRange;
//    
//    //替换选中的文本
//    [attributeStrM replaceCharactersInRange:range withAttributedString:attributeStr];
//    
//    //为属性文本添加字体
//    [attributeStrM addAttribute:NSFontAttributeName value:self.textView.font range:NSMakeRange(range.location, attributeStr.length)];
//    
//    //重新赋值给textView的属性文本
//    self.textView.attributedText = attributeStrM;
//    
//    //调整光标的位置 到插入属性文本的后面
//    self.textView.selectedRange = NSMakeRange(range.location + 1, 0);
//}


#pragma mark - 数据源方法 
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.emojiPackages.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    ZDEmojiPackage *emojiPackage = self.emojiPackages[section];
    
    return emojiPackage.emoticons.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
    
    ZDEmojiPackage *package = self.emojiPackages[indexPath.section];
    
    cell.emoji = package.emoticons[indexPath.item];
    
    return cell;
}

//滚动停止的时候调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //获取当前section
    NSIndexPath *indexPath = [self.collectionView indexPathsForVisibleItems].firstObject;
    
    NSUInteger index = indexPath.section + ZDBaseIndex;
    
    UIButton *btn = (UIButton *)[self.toolBar viewWithTag:index];
    
    [self switchBtn:btn];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZDEmojiPackage *package = self.emojiPackages[indexPath.section];
    
    ZDEmoji *emoji = package.emoticons[indexPath.item];
    
    //textView插入文本
    [self.textView insertEmojiWith:emoji];
    
    if (indexPath.section != 0)
    {
        //更新最近表情包  如果是第0组，最近表情包中的表情 则不需要再添加到最近表情包中
        [ZDEmojiPackage updateRecentPackageWithEmoji:emoji];
    }
    
}



#pragma mark 懒加载
- (UIToolbar *)toolBar
{
    if (!_toolBar)
    {
        _toolBar = [[UIToolbar alloc] init];
    }
    
    return _toolBar;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[ZDCollectionViewFlowLayout alloc] init]];
    }
    
    return _collectionView;
}

- (NSArray *)emojiPackages
{
    if (!_emojiPackages)
    {
        _emojiPackages = [ZDEmojiPackage emojiPackages];
    }
    
    return _emojiPackages;
}


- (void)dealloc
{
    ZDLog(@"表情控制器挂了");
}

@end
